<template>
  <div class="search">
    <div class="search-box">
      <div class="bx clearfix">
        <van-search
          shape="round"
          placeholder="请输入搜索关键词"
          v-model="value"
          @input="searchCommodity"
        />
        <div class="serBack" @click="back">取消</div>
      </div>
      <div class="product-box clearfix">
        <div
          class="product-item fl"
          :class="[index % 2 == 0 ? 'p-left' : 'p-right']"
          v-for="(item, index) in searchData"
          :key="index"
        >
          <div class="p-img" @click="viewProductInfo(item.pid)">
            <img class="auto-img" :src="item.smallImg" alt="" />
          </div>
          <div class="pro-name one-text">{{ item.name }}</div>
          <div class="clearfix">
            <div class="pro-price fl">￥{{ item.price }}</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import "../assets/less/search.less";
export default {
  data() {
    return {
      value: "",
      searchData: [],
    };
  },
  methods: {
    back() {
      this.$router.go(-1);
    },
    //搜索商品
    searchCommodity() {
      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
        loadingType: "spinner",
      });
      this.axios({
        method: "GET",
        url: "/search",
        //如果get请求，参数需要放在params, 如果是post请求,参数需要放在data
        params: {
          appkey: this.appkey,
          name: this.value,
        },
      })
        .then((result) => {
          this.$toast.clear();
          console.log(" search result ==> ", result);
          if (result.data.code == "Q001") {
            if (result.data.result.length != 0) {
              this.searchData = result.data.result;
            } else {
              this.$toast("无相关商品,很抱歉!");
            }
          }
        })
        .catch((err) => {
          this.$toast.clear();
        });
    },
    //查看商品详情
    viewProductInfo(pid) {
      this.$router.push({ name: "Detail", query: { pid } });
    },
  },
};
</script>
